package ua.org.nuos.sdms.clientgui.client.handlers;

import ua.org.nuos.sdms.clientgui.client.context.Messages;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.client.events.LoginEvent;
import ua.org.nuos.sdms.clientgui.client.events.UserChangedEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.LoginListener;
import ua.org.nuos.sdms.clientgui.client.util.ComponentUtil;
import ua.org.nuos.sdms.clientgui.client.view.LoginWindow;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.clientgui.server.exceptions.AuthenticationException;
import ua.org.nuos.sdms.clientgui.server.services.ServiceLocator;

import javax.ejb.EJBAccessException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 19.02.12
 * Time: 20:30
 * To change this template use File | Settings | File Templates.
 */
public class LoginHandler implements LoginListener {
    private static final Logger logger = Logger.getLogger(LoginHandler.class.getName());

    @Override
    public void doLogin(LoginEvent event) {
        ServiceLocator serviceLocator = AppProxy.getInstance().getServiceLocator();
        try {
            try {
                serviceLocator.getLoginService().login(AppProxy.getInstance().getAppTools().getRequest(), event.getLogin(), event.getPassword());
                AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new UserChangedEvent());
                ComponentUtil.closeWindow(LoginWindow.ID);
            } catch (AuthenticationException e) {
                logger.log(Level.WARNING, "Authentication exception", e);
                AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.AUTHENTICATION_ERROR));
                serviceLocator.getLoginService().logout(AppProxy.getInstance().getAppTools().getRequest());
            } catch (EJBAccessException e) {
                logger.log(Level.WARNING, "Authentication exception", e);
                AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.AUTHENTICATION_ERROR));
                serviceLocator.getLoginService().logout(AppProxy.getInstance().getAppTools().getRequest());
            }
        } catch (Exception ex) {
            logger.log(Level.WARNING, "Authentication error", ex);
            AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.ACTION_ERROR));
        }
    }
}

